package utils

import (
	"fmt"
	"os"
	"path/filepath"
)

func DirSize(path string) (int64, error) {
	var size int64
	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			size += info.Size()
		}
		return nil
	})
	return size, err
}

func HumanSize(size int64) string {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
		TB = GB * 1024
	)

	f := float64(size)
	switch {
	case size >= TB:
		return fmt.Sprintf("%.1fT", f/TB)
	case size >= GB:
		return fmt.Sprintf("%.1fG", f/GB)
	case size >= MB:
		return fmt.Sprintf("%.1fM", f/MB)
	case size >= KB:
		return fmt.Sprintf("%.1fK", f/KB)
	default:
		return fmt.Sprintf("%.1fB", f)
	}
}
